<?php
/**
 * licenses : MIT
 * creatTime: 2020/5/17
 * author : weblinuxgame
 * filename: TransfromTrait.php
 */

namespace App\Core\Traits\Api;

use ArrayAccess;
use Illuminate\Support\Str;
use Illuminate\Contracts\Support\Arrayable;

/**
 * Trait TransformTrait
 * @package App\Core\Traits\Api
 */
trait TransformTrait
{
    /**
     * 数组
     * @param $data
     * @return array|int|string|object
     */
    public static function arrays($data)
    {
        if ($data instanceof Arrayable) {
            return $data->toArray();
        }
        if ($data instanceof ArrayAccess) {
            $tmp = [];
            foreach ($data as $key => $value) {
                $tmp[$key] = $value;
            }
        }
        return $data;
    }

    /**
     * 转换
     * @param array $data
     * @return array
     */
    public static function transform(array &$data): array
    {
        foreach ($data as $key => $item) {
            $k = Str::camel($key);
            if ($k === $key) {
                $item = self::arrays($item);
                if (is_array($item)) {
                    $data[$key] = self::transform($item);
                }
                continue;
            }
            if (is_object($item)) {
                $item = self::arrays($data);
            }
            if (is_array($item)) {
                $item = static::transform($item);
            }
            $data[$k] = $item;
            unset($data[$key]);
        }
        return $data;
    }

}
